package com.yksj.healthtalk.ui.friend;

import java.util.ArrayList;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;

import sfs2x.client.core.SFSEvent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.yksj.healthtalk.adapter.DoctorAdapter;
import com.yksj.healthtalk.adapter.DoctorAdapter.onClickFriendAttentionListener;
import com.yksj.healthtalk.adapter.DoctorAdapter.onClickFriendHeadListener;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 挂号 付费
 * 
 * @author Administrator
 * 
 */
public class unRegisterFragment extends Fragment implements
		OnItemClickListener, OnRefreshListener2<ListView>,
		onClickFriendAttentionListener, onClickFriendHeadListener{

	private PullToRefreshListView mPullToRefreshListView;
	private CustomerInfoEntity mCustomerInfoEntity;
	private DoctorAdapter adapter;
	private ArrayList<CustomerInfoEntity> entities;
	private String pageMark = "-100000";
	private ListView mListView;
	private CustomerInfoEntity cacheCustomerInfoEntity;
	private AppData mAppData;
	private IntentFilter filter;
	private Context context;
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_FRIEND)) {
				LodingFragmentDialog.dismiss(getFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(context, R.string.groupNewFail);
				} else {
					FriendHttpUtil.requestAttentionTofriendsResult(context,
							cacheCustomerInfoEntity, mAppData);
					adapter.notifyDataSetChanged();
				}
			} else if (action.equals(SFSEvent.CONNECTION_LOST)) {
			}
		}

	};

	@Override  
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mAppData = HTalkApplication.getAppData();
		mCustomerInfoEntity = getArguments().getParcelable(
				"mCustomerInfoEntity");
		View v = inflater.inflate(R.layout.register_layout, container, false);
		initWidget(v);
		initData(v);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
	}

	public static Fragment getInstance(CustomerInfoEntity mCustomerInfoEntity) {
		unRegisterFragment fragment = new unRegisterFragment();
		Bundle args = new Bundle();
		args.putParcelable("mCustomerInfoEntity", mCustomerInfoEntity);
		fragment.setArguments(args);
		return fragment;
	}

	private void initData(View v) {
		entities = new ArrayList<CustomerInfoEntity>();
		adapter = new DoctorAdapter(getActivity(), entities, true);
		adapter.setonClickFriendAttentionListener(this);
		adapter.setonClickFriendHeadListener(this);
		mPullToRefreshListView.setOnRefreshListener(this);
		mListView = mPullToRefreshListView.getRefreshableView();
		mListView.addHeaderView(LayoutInflater.from(getActivity()).inflate(
				R.layout.list_line_layout, null));
		mListView.setOnItemClickListener(this);
		mListView.setAdapter(adapter);
		if (mCustomerInfoEntity == null) {
			mCustomerInfoEntity = new CustomerInfoEntity();
		}
		mCustomerInfoEntity.setType(1);
		mCustomerInfoEntity.setFlag(pageMark);
		mCustomerInfoEntity.setId(SmartFoxClient.getSmartFoxClient()
				.getUserId());
		mCustomerInfoEntity.setOrderOnOff(1);
		getDoctors();
	}

	private void getDoctors() {
		HttpRestClient.doHttpRequestSearchFriends(mCustomerInfoEntity, 1,
				new ObjectHttpResponseHandler(getActivity()) {

					@Override
					public Object onParseResponse(String content) {
						ArrayList<CustomerInfoEntity> mCustomerInfoEntities = FriendHttpUtil
								.jsonAnalysisFriendEntity(content, false);
						return mCustomerInfoEntities;
					}

					@Override
					public void onSuccess(int statusCode, Object response) {
						if (response != null) {
							responseSuccess(0, 0,
									(ArrayList<CustomerInfoEntity>) response);
						}
						super.onSuccess(statusCode, response);
					}

				});
	}

	private void initWidget(View v) {
		// TODO Auto-generated method stub
		mPullToRefreshListView = (PullToRefreshListView) v
				.findViewById(R.id.hall);
		mPullToRefreshListView.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		try {
			Intent intent = new Intent(getActivity(), DoctorMainActivity.class);
			intent.putExtra("id", entities.get(position - 2).getId());
			intent.putExtra("type", "0");
			startActivity(intent);
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	public void responseSuccess(int type, int sourceType,
			final ArrayList<CustomerInfoEntity> c) {
		boolean isFristPage;
		if (pageMark.equals("-100000")) {
			entities.clear();
			isFristPage = true;
		}
		isFristPage = false;
		entities.addAll(c);
		pageMark = adapter.getPageMark(isFristPage);// 翻页标记
		LodingFragmentDialog.dismiss(getChildFragmentManager());
		adapter.notifyDataSetChanged();
		mPullToRefreshListView.onRefreshComplete();
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		pageMark = "-100000";
		mCustomerInfoEntity.setFlag(pageMark);
		getDoctors();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		mCustomerInfoEntity.setFlag(pageMark);
		getDoctors();
	}

	@Override
	public void onClickFriendHead(CustomerInfoEntity entity, int positon) {
		// Intent intent = new Intent();
		// intent.setClass(getActivity(), FriendInformUI.class);
		// // intent.putExtra("PersonInfo", entity);
		// intent.putExtra("positon", positon);
		// intent.putExtra("id", entity.getId());
		// startActivityForResult(intent, 0);
		Intent intent = new Intent(getActivity(), DoctorMainActivity.class);
		intent.putExtra("id", entity.getId());
		intent.putExtra("type", "0");
		startActivity(intent);
	}

	@Override
	public void onClickFriendAttention(int attentioned,
			CustomerInfoEntity entity, int positon) {
		if (!SmartFoxClient.getSmartFoxClient().isConnected()) {
			ToastUtil.showLong(getActivity(), "与服务器连接错误");
			return;
		}
		cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(
				getActivity(),
				null, entity);
	}

	@Override
	public void onStop() {
		unRegisterReceiver(getActivity());
		super.onStop();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0 && resultCode == 0) {
			if (data != null && data.hasExtra("mFriendInformUI")) {
				entities.set(data.getIntExtra("positon", -1),
						(CustomerInfoEntity) data
								.getParcelableExtra("mFriendInformUI"));
				adapter.notifyDataSetChanged();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}



	@Override
	public void onStart() {
		registerReceiver(getActivity());
		super.onStart();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	public void registerReceiver(Context context) {
		filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_FRIEND);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		context.registerReceiver(receiver, filter);
	}

	public void unRegisterReceiver(Context context) {
		try {
			context.unregisterReceiver(receiver);
		} catch (Exception e) {
			System.err.println(e);
		}
	}

}
